package com.bwie.filter;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import javax.annotation.Resource;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * @author : LeiMingkun
 * @date : 2024-09-09 09:51
 * @description : GateWayFilter
 **/
@Component
public class GateWayFilter implements GlobalFilter, Ordered {
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        String url = request.getPath().toString();
        if(url.contains("/user/user/getLogin")){
            return chain.filter(exchange);
        }
        if(url.contains("/user/user/sendCode")){
            return chain.filter(exchange);
        }
        if(url.contains("/user/user/findUser")){
            return chain.filter(exchange);
        }
        ValueOperations<String, String> opsForValue = stringRedisTemplate.opsForValue();
        String token = opsForValue.get("token");
        if(Objects.isNull(token)){
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }else {
            Long expire = stringRedisTemplate.getExpire("token", TimeUnit.MINUTES);
            if(expire<1){
                stringRedisTemplate.expire("token",2,TimeUnit.MINUTES);
            }
            return chain.filter(exchange);
        }
    }

    @Override
    public int getOrder() {
        return 0;
    }
}